#include "../tools.h"


class LRUCache {
public:
    int size;
    list<pair<int, int>> data;
    unordered_map<int, list<pair<int, int>>::iterator> map;

    LRUCache(int capacity) {
        size = capacity;
    }
    
    int get(int key) {
        if(map.find(key) == map.end()) return -1;
        else{
            data.splice(data.begin(), data, map[key]);
            return map[key]->second;
        }
    }
    
    void put(int key, int value) {
        if(get(key) != -1) map[key]->second = value;
        else{
            if(data.size() == size){
                int dkey = data.back().first;
                data.pop_back();
                map.erase(dkey);
            }
            data.emplace_front(key, value);
            map[key] = data.begin();
        }
    }
};



int main(int argc, char const *argv[])
{
    LRUCache* obj = new LRUCache(2);
    int res;


    obj->put(1, 1);
    obj->put(2, 2);
    cout << obj->get(1); 
    cout << endl;

    obj->put(3, 3);

    cout << obj->get(2);
    cout << endl;

    obj->put(4, 4); // 该操作会使得关键字 1 作废，缓存是 {4=4, 3=3}
    cout << obj->get(1);    // 返回 -1 (未找到)
    cout << endl;
    cout << obj->get(3);    // 返回 3
    cout << endl;

    cout <<obj->get(4);
    cout << endl;

    
    return 0;
}
